# encoding=utf8

from flask import request
from flask_restplus import Resource
from car.app import api, db
from car.customer import dto
from car.customer.validator import validate_customer

ns = api.namespace("customers", description="Customers Module")


@ns.route('/create')
class AddCustomer(Resource):
    @api.expect(dto.create_customer)
    def post(self):
        info = request.json
        validation = validate_customer(info)
        if not validation['valid']:
            return validation['comment'], 400

        res = db.add('customers', info)
        return res


@ns.route('/search')
class SearchCustomer(Resource):
    @api.expect(dto.customer_basic)
    def get(self):
        info = request.json
        table = db.tables.get('customers')

        sql = 'SELECT * FROM customers'
        conditions = []
        for key in info:
            if key in table.columns:
                cond = f"{key}=:{key}"
                conditions.append(cond)

        if conditions:
            sql += ' WHERE ' + ' and '.join(conditions)

        res = db.query(sql, **info)
        return res


@ns.route('/delete')
class DeleteCustomer(Resource):
    @api.expect(dto.delete_customer)
    def delete(self):
        info = request.json
        sql1 = f'DELETE FROM orders WHERE customer_id=:id'
        sql2 = f'DELETE FROM address WHERE customer_id=:id'
        sql3 = f'DELETE FROM customers WHERE id=:id'

        with db.session() as s:
            db.execute(sql1, **info)
            db.execute(sql2, **info)
            db.execute(sql3, **info)


@ns.route('/update')
class UpdateCustomer(Resource):
    @api.expect(dto.update_customer)
    def post(self):
        info = request.json
        table = db.tables.get('customers')
        conditions = []
        for key in info:
            if key in table.columns and key != 'id':
                cond = f"{key}=:{key}"
                conditions.append(cond)

        if conditions:
            sql = f'UPDATE customers SET ' + ', '.join(conditions) + ' WHERE id=:id'

        res = db.execute(sql, **info)

        # return res

